package com.awspaas.user.apps.sts.service;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.ProcessInstance;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.TaskInstance;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.commons.htmlframework.HtmlPageTemplate;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.server.RequestParams;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.exception.BPMNError;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSONObject;
import com.awspaas.user.apps.sts.util.ButttonPostMessageUtil;
import com.awspaas.user.apps.sts.util.DbsqlUtil;
import com.awspaas.user.apps.sts.util.MiddleLogUtil;
import com.awspaas.user.apps.sts.util.UitlIs;
import jodd.util.StringUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Title: StsBtnSevice
 * @Package com.awspaas.user.apps.sts.Service.StsBtnSevice
 * @Description: 提交，保存按钮触发动作基础控制
 * @Author zhoujianchen
 * @Email
 * @Date 2022/9/04
 */
public class StsBtnSevice {
    /**
     * 按钮点击后触发动作（）
     * @param uc
     * @param re
     * @return
     */
    public String BtnClickEvent(UserContext uc, RequestParams re) {
        //返回类型Json数据
        JSONObject jsonObject = new JSONObject();
        //定义参数Map，赋值
        HashMap<String,String> paramsMap = new HashMap<>();
        /*paramsMap.put("APPLICATIONNAME")
        paramsMap.put("TASKINSTID")
        paramsMap.put("PROCESSINSTID")
        paramsMap.put("PROCESSDEFID")
        paramsMap.put("BUSINESSID")
        paramsMap.put("BUTTONID")
        paramsMap.put("BUSINESSSTATUSID")
        paramsMap.put("BUSINESSSTATUSTIME")
        paramsMap.put("BPMBUTTONID")
        paramsMap.put("BPMBUTTONNAME")
        paramsMap.put("CREATELOGDATETIME")
        paramsMap.put("SENDREFERENCE")
        paramsMap.put("PARTICIPATION")
        paramsMap.put("BUTTONSTATUS")
        paramsMap.put("BUSINESSRESULT")
        paramsMap.put("BUSINESSSTATUSTIME")
        paramsMap.put("NOTES")
        paramsMap.put("EXTINFO")*/
        //获取参数（任务id,流程id,按钮类型）
        String taskInstID = re.get("TASKINSTID");
        String processInstID = re.get("PROCESSINSTID");
        String bpmButtonID = re.get("BPMBUTTONID");
        String type = re.get("type");
        //获取流程定义id
        ProcessInstance  processInstance = SDK.getProcessAPI().getInstanceById(processInstID);
        String processDefId = processInstance.getProcessDefId();
        TaskInstance taskInstance = SDK.getTaskAPI().getTaskInstance(taskInstID);
        //节点id
        String activityDefId = "";
        try{
            activityDefId = taskInstance.getActivityDefId();
        }catch (Exception e){
            e.printStackTrace();
        }
        //三方按钮信息
        RowMap otherButtonRowMap = DBSql.getMap("SELECT * FROM BO_PS_BUSINESS_BUTTON_REGISTER WHERE BPMBUTTONNAME = ? AND " +
                "PROCESS_DEFID = ? AND ACTIVITY_DEFID = ?", new Object[]{bpmButtonID, processDefId, activityDefId});
        System.out.println("按钮ID" + bpmButtonID + ";流程定义ID" + processDefId + ";流程节点ID" + activityDefId);
        System.out.println("三方按钮信息："+otherButtonRowMap);
        if (null!=otherButtonRowMap && !otherButtonRowMap.isEmpty()) {
            //按钮有效性
            String button_effectiveness = otherButtonRowMap.getString("BUTTON_EFFECTIVENESS");
            if (button_effectiveness.equals("01")) {
                //查询接口日志表
                //RowMap awsLogRowMap = DBSql.getMap("SELECT * FROM BO_EU_INTERFACE_LOG WHERE TO_DO_PROCESSINSTID = ? AND TO_DO_ID = ? AND SUCCESS_OR_FAILURE = ?", new Object[]{processInstID, taskInstID, "200"});
                //业务ID
                //String businessID = awsLogRowMap.getString("TO_DO_BUSINESSID");
                BO detail = SDK.getBOAPI().query("BO_EU_INTERFACE_LOG").addQuery("TO_DO_PROCESSINSTID=", "processInstID").detail();
                String businessID = "";
                //业务名称（获取方式未定义）
                String businessName = "";
                //查询业务状态对应表
                /*RowMap BARowMap = DBSql.getMap("SELECT * FROM BO_PS_BUSINESS_ACTIVITY WHERE PROCESS_DEFID = ? AND ACTIVITY_DEFID = ? AND EFFECTIVENESS = ?", new Object[]{processDefId, activityDefId, "01"});
                //业务状态
                String businessstatusid = BARowMap.getString("BUSINESSSTATUSID");
                String businessstatusname = BARowMap.getString("BUSINESSSTATUSNAME");*/
                paramsMap.put("APPLICATIONNAME", otherButtonRowMap.getString("APPLICATIONNAME"));
                paramsMap.put("TASKINSTID", taskInstID);
                paramsMap.put("PROCESSINSTID", processInstID);
                paramsMap.put("PROCESSDEFID", processDefId);
                paramsMap.put("BUSINESSID", businessID);
                paramsMap.put("BUSINESSNAME", businessName);
               /* paramsMap.put("BUSINESSSTATUSID", businessstatusid);
                paramsMap.put("BUSINESSSTATUSNAME", businessstatusname);*/
                paramsMap.put("BUTTONID", otherButtonRowMap.getString("APPBUTTONID"));
                paramsMap.put("BUTTONNAME", otherButtonRowMap.getString("APPBUTTONNAME"));
                paramsMap.put("BUTTONURL", otherButtonRowMap.getString("APPBUTTONURL"));
                paramsMap.put("BUTTONTYPE", otherButtonRowMap.getString("APPBUTTONTYPE"));
                paramsMap.put("BPMBUTTONID", bpmButtonID);
                paramsMap.put("BPMBUTTONNAME", otherButtonRowMap.getString("BUTTONNAME"));
                //解析extinfo 为data赋值
                String extinfo = otherButtonRowMap.getString("EXTINFO");
                if (StringUtil.isNotEmpty(extinfo)) {
                    JSONObject extinfoJO = JSONObject.parseObject(extinfo);
                    Map<String, String> extinfoMap = new HashMap<>();
                    for (Map.Entry<String, Object> entry : extinfoJO.entrySet()) {
                        extinfoJO.put(entry.getKey(), String.valueOf(entry.getValue()));
                    }
                    Set<String> extinfoKeySet = extinfoMap.keySet();
                    for (String extinfoKey : extinfoKeySet) {
                        paramsMap.put(extinfoKey, extinfoMap.get(extinfoKey));
                    }
                }
                //工具类
                ButttonPostMessageUtil butttonPostMessageUtil = new ButttonPostMessageUtil();
                MiddleLogUtil middleLogUtil = new MiddleLogUtil();
                //返回数据赋值
                jsonObject.put("hasOther", true);
                jsonObject.put("button_effectiveness", true);
                //判断按钮是否为提交按钮
                boolean isTracneType = false;
                //判断是否存在业务中间表中是否存在该按钮数据
                boolean hasLog = butttonPostMessageUtil.hasLog(paramsMap);
                boolean isTransactDealPass = false;
                boolean isDeal = false;
                //判断业务状态是否相同
                boolean isEquals = false;
                boolean isStateNull = new UitlIs().isStateNull(taskInstID, bpmButtonID);

                if ("0".equals(type)) {
                    //是否
                    isDeal = new UitlIs().IsTransactDeal(taskInstID, bpmButtonID, activityDefId);
                    //是否通过
                    isTransactDealPass = new UitlIs().IsTransactPass(taskInstID, bpmButtonID, activityDefId);
                    isTracneType = true;
                } else if ("1".equals(type)) {//判断是否是驳回按钮
                    System.out.println("驳回");
                    isDeal = new UitlIs().IsRefuseDeal(taskInstID, bpmButtonID, activityDefId);
                    isTransactDealPass = new UitlIs().IsRefuePass(taskInstID, bpmButtonID, activityDefId);

                } else {
                    //其他按钮处理结果
                    isDeal = new UitlIs().IsOtherHasResult(taskInstID, bpmButtonID, activityDefId);
                    //isDeal = false;
                    isTransactDealPass = new UitlIs().IsNotTransact(taskInstID, bpmButtonID, activityDefId);
                }
                isEquals = new UitlIs().isBussionStatus(taskInstID,bpmButtonID,activityDefId);
                String msga = new UitlIs().reBussionStatus(taskInstID,bpmButtonID,activityDefId);
                jsonObject.put("msga",msga);
                jsonObject.put("dealResult", isDeal);
                jsonObject.put("isEquals",isEquals);
                if (!isDeal) {
                    //插入按钮点击日志
                    String insertLogState = middleLogUtil.InsertBtnLog(paramsMap);
                    if (insertLogState.equals("insertOK")) {
                        RowMap signBtnLogMax = middleLogUtil.getSignBtnLogMax(paramsMap, bpmButtonID);
                        paramsMap.put("CREATELOGTIMESTAMP", signBtnLogMax.getString("CREATELOGTIMESTAMP"));
                        jsonObject.put("data", paramsMap);
                    }
                    return jsonObject.toString();
                } else {
                    jsonObject.put("isTransactDealPass", isTransactDealPass);
                    if (isTransactDealPass) {
                        RowMap signBtnLogMax = middleLogUtil.getSignBtnLogMax(paramsMap, bpmButtonID);
                        paramsMap.put("CREATELOGTIMESTAMP", signBtnLogMax.getString("CREATELOGTIMESTAMP"));
                        jsonObject.put("data", paramsMap);
                        return jsonObject.toString();
                    } else {
                        if (isTracneType) {
                            boolean IsOtherDeal = new UitlIs().IsOtherDeal(taskInstID, bpmButtonID, activityDefId);
                            if (IsOtherDeal) {
                                jsonObject.put("isTransactDeal", IsOtherDeal);
                                jsonObject.put("isStateNull", isStateNull);

                                if (isStateNull) {
                                    jsonObject.put("msg", "该操作已提交未完成，请勿重复提交，若有疑问，请联系系统管理员");
                                    RowMap signBtnLogMax = middleLogUtil.getSignBtnLogMax(paramsMap, bpmButtonID);
                                    paramsMap.put("CREATELOGTIMESTAMP", signBtnLogMax.getString("CREATELOGTIMESTAMP"));
                                } else {

                                    //更新按钮点击日志
                                    middleLogUtil.UpdateBtnLog(paramsMap);
                                    RowMap signBtnLogMax = middleLogUtil.getSignBtnLogMax(paramsMap, bpmButtonID);
                                    paramsMap.put("CREATELOGTIMESTAMP", signBtnLogMax.getString("CREATELOGTIMESTAMP"));
                                    jsonObject.put("data", paramsMap);
                                    return jsonObject.toString();
                                }

                            } else {
                                jsonObject.put("isTransactDeal", IsOtherDeal);
                                jsonObject.put("hasLog", hasLog);
                                String msg = new UitlIs().getMsg(taskInstID, bpmButtonID, activityDefId);
                                jsonObject.put("msg", msg);
                                RowMap signBtnLogMax = middleLogUtil.getSignBtnLogMax(paramsMap, bpmButtonID);
                                paramsMap.put("CREATELOGTIMESTAMP", signBtnLogMax.getString("CREATELOGTIMESTAMP"));
                                jsonObject.put("data", paramsMap);
                                return jsonObject.toString();
                            }
                        } else if ("1".equals(type)) {//判断是否是驳回按钮
                            boolean IsOtherDeal = new UitlIs().IsOtherNullDeal(taskInstID, bpmButtonID, activityDefId);
                            if (IsOtherDeal) {
                                jsonObject.put("isTransactDeal", IsOtherDeal);
                                jsonObject.put("isStateNull", isStateNull);
                                if (isStateNull) {
                                    jsonObject.put("msg", "该操作已提交未完成，请勿重复提交，若有疑问，请联系系统管理员");
                                } else {

                                    //更新按钮点击日志
                                    middleLogUtil.UpdateBtnLog(paramsMap);
                                    RowMap signBtnLogMax = middleLogUtil.getSignBtnLogMax(paramsMap, bpmButtonID);
                                    paramsMap.put("CREATELOGTIMESTAMP", signBtnLogMax.getString("CREATELOGTIMESTAMP"));
                                    jsonObject.put("data", paramsMap);
                                    return jsonObject.toString();
                                }

                            } else {
                                jsonObject.put("isStateNull", isStateNull);
                                jsonObject.put("hasLog", hasLog);
                                if (isStateNull) {
                                    if (hasLog) {
                                        jsonObject.put("msg", "该操作已提交未完成，请勿重复提交，若有疑问，请联系系统管理员");
                                        // RowMap signBtnLogMax = middleLogUtil.getSignBtnLogMax(paramsMap, bpmButtonID);
                                        // paramsMap.put("CREATELOGTIMESTAMP", signBtnLogMax.getString("CREATELOGTIMESTAMP"));
                                    } else {
                                        String insertLogState = middleLogUtil.InsertBtnLog(paramsMap);
                                        if (insertLogState.equals("insertOK")) {
                                            RowMap signBtnLogMax = middleLogUtil.getSignBtnLogMax(paramsMap, bpmButtonID);
                                            paramsMap.put("CREATELOGTIMESTAMP", signBtnLogMax.getString("CREATELOGTIMESTAMP"));
                                        }
                                    }
                                    jsonObject.put("data", paramsMap);
                                    return jsonObject.toString();
                                } else {
                                    //更新按钮点击日志
                                    middleLogUtil.UpdateBtnLog(paramsMap);
                                    RowMap signBtnLogMax = middleLogUtil.getSignBtnLogMax(paramsMap, bpmButtonID);
                                    paramsMap.put("CREATELOGTIMESTAMP", signBtnLogMax.getString("CREATELOGTIMESTAMP"));
                                    jsonObject.put("data", paramsMap);
                                    return jsonObject.toString();
                                }
                            }


                        }
                    }
                /*else {
                    jsonObject.put("hasLog",true);
                    //判断按钮是否办理通过
                    boolean isTransactDealPass = butttonPostMessageUtil.IsTransactDealPass(paramsMap);
                    if (isTransactDealPass) {
                        jsonObject.put("isTransactDealPass",true);
                        jsonObject.put("msg","按钮办理成功");
                    } else {
                        jsonObject.put("isTransactDealPass",false);
                        boolean stateNull = butttonPostMessageUtil.isStateNull(paramsMap);
                        //判断按钮状态是否为空
                        if (stateNull) {
                            jsonObject.put("msg","该按钮办理业务尚未结束，请稍后重试");
                        } else {
                            String msg = butttonPostMessageUtil.getMsg(paramsMap);
                            jsonObject.put("msg",msg);
                        }
                    }
                }*/
                }
            }else {
                jsonObject.put("button_effectiveness",false);
                jsonObject.put("msg","当前按钮已失效");
            }
        } else {
            jsonObject.put("hasOther",false);
            jsonObject.put("msg","当前按钮未建立映射关系");
        }
        return jsonObject.toString();
    }

    /**
     * @methodName: postMessage交互后查询最新日志记录
     * @param:
     * @return:
     * @description:
     * @auther: Lizj
     * @date: 2022/10/21 17:51
     */
    public String getSignBtnLogMax(UserContext uc, RequestParams re) {
        MiddleLogUtil middleLogUtil = new MiddleLogUtil();
        Map<String, String> paramsMap = re.asMap();
        //获取参数（任务id,按钮id）
        String taskInstID = re.get("TASKINSTID");
        String bpmButtonID = re.get("BPMBUTTONID");
        //获取任务实例
        TaskInstance taskInstance = SDK.getTaskAPI().getTaskInstance(taskInstID);
        //节点id
        String activityDefId = "";
        try{
            activityDefId = taskInstance.getActivityDefId();
        }catch (Exception e){
            e.printStackTrace();
        }
        //判断业务状态是否相同
        boolean isEquals = false;
        isEquals = new UitlIs().isBussionStatus(taskInstID,bpmButtonID,activityDefId);
        String msga = new UitlIs().reBussionStatus(taskInstID,bpmButtonID,activityDefId);
        String bpmbuttonid = re.get("BPMBUTTONID");
        RowMap signBtnLogMax = middleLogUtil.getSignBtnLogMax(paramsMap, bpmbuttonid);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msga",msga);
        jsonObject.put("data", signBtnLogMax);
        jsonObject.put("isEquals",isEquals);
        return jsonObject.toString();
    }
    /**
     * 控制审批留言显隐
     * @param uc
     * @param re
     * @return
     */
    public String MsgShowEvent(UserContext uc, RequestParams re) {
        //获取参数（任务实例id,流程实例id,按钮ID）
        String taskInstID = re.get("TASKINSTID");
        String processInstID = re.get("PROCESSINSTID");
        String bpmButtonID = re.get("BPMBUTTONID");
        JSONObject jsonObject = new JSONObject();
        //获取流程定义id
        ProcessInstance  processInstance = SDK.getProcessAPI().getInstanceById(processInstID);
        String processDefId = processInstance.getProcessDefId();
        TaskInstance taskInstance = SDK.getTaskAPI().getTaskInstance(taskInstID);
        //节点id
        String activityDefId = "";
        try{
            activityDefId = taskInstance.getActivityDefId();
        }catch (Exception e){
            throw new BPMNError("5001","节点定义ID未找到，请联系管理员！");
        }
        String buttonShow =   DBSql.getString("SELECT BUTTONSHOWHIDE FROM BO_PS_BUSINESS_BUTTON_REGISTER WHERE BPMBUTTONNAME = ? AND " +
                "PROCESS_DEFID = ? AND ACTIVITY_DEFID = ?", new Object[]{bpmButtonID, processDefId, activityDefId});
        boolean isShow = false;
        if (StringUtil.isNotEmpty(buttonShow)){
            if ("1".equals(buttonShow)){
                isShow=true;
            }
        }
        //三方按钮信息
        RowMap otherButtonRowMap = DBSql.getMap("SELECT * FROM BO_PS_BUSINESS_BUTTON_REGISTER WHERE BPMBUTTONNAME = ? AND " +
                "PROCESS_DEFID = ? AND ACTIVITY_DEFID = ?", new Object[]{bpmButtonID, processDefId, activityDefId});
        System.out.println("按钮ID" + bpmButtonID + ";流程定义ID" + processDefId + ";流程节点ID" + activityDefId);
        System.out.println("三方按钮信息："+otherButtonRowMap);
        if (null!=otherButtonRowMap && !otherButtonRowMap.isEmpty()) {
            String isCompareLoading = otherButtonRowMap.getString("ISCOMPARELOADING");
            if ("1".equals(isCompareLoading)){
                jsonObject.put("isCompareLoading",true);
            }else {
                jsonObject.put("isCompareLoading",false);
            }

        }else {
            jsonObject.put("isCompareLoading",false);
        }
        if (otherButtonRowMap!=null){
            String applicationName = otherButtonRowMap.getString("APPLICATIONNAME");

            String thButton = SDK.getDictAPI().getValue("com.awspaas.user.apps.sts","SYSTME_REBUTTON",applicationName);
            System.out.println(thButton);
            jsonObject.put("thButton",thButton);
        }
        jsonObject.put("isShow",isShow);

        return  jsonObject.toString();
    }


}
